package com.gb.web.common.utils;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json 工具类
 */
public class JSONUtil {
	
	// 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();
    
    /**
     * 字符串解析为Object
     * @param text
     * @return
     */
    public static Object parse(String text){
    	try {
    		Object t = MAPPER.readValue(text, Object.class);
            return t;
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 对象转json字符串
     * @param data
     * @return
     */
    public static String toJSON(Object data) {
    	try {
			String string = MAPPER.writeValueAsString(data);
			return string;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    /**
     * 对象转byte数组
     * @param data
     * @return
     */
    public static byte[] toJSONBytes(Object data) {
    	try {
			String result = MAPPER.writeValueAsString(data);
			if (result != null && !result.equals("")) {
				return result.getBytes();
			}
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    /**
     * 将json结果集转化为对象，泛型方法
     * @param jsonData json数据
     * @param clazz 对象中的object类型
     * @return
     */
    public static <T> T parse(String text, Class<T> classType) {
        try {
            T t = MAPPER.readValue(text, classType);
            return t;
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 将json数据转换成pojo对象list
     * @param text
     * @param classType
     * @return
     */
    public static <T> List<T> parseList(String text, Class<T> classType) {
    	try {
    		JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, classType);
    		List<T> list = MAPPER.readValue(text, javaType);
    		return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	return null;
    }
}
